package com.xxd.spring.boot.demo.zhuhongbing.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xxd.spring.boot.demo.zhuhongbing.entity.User;
import com.xxd.spring.boot.demo.zhuhongbing.util.DateUtil;
import com.xxd.spring.boot.demo.zhuhongbing.util.UserManageUtil;
import org.apache.ibatis.reflection.MetaObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        boolean createTime=metaObject.hasSetter("createTime");
        if(createTime){
            Object createTimeValue=metaObject.getValue("createTime");
            if(Objects.isNull(createTimeValue)){

                metaObject.setValue("createTime", DateUtil.dateFmt(new Date()));
            }
        }
        boolean createBy=metaObject.hasSetter("createBy");
        if(createBy){
            Object createByValue=metaObject.getValue("createBy");
            if(Objects.isNull(createByValue)){
                User user=UserManageUtil.get();
                metaObject.setValue("createBy",user.getUsername());
            }
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        boolean updateTime=metaObject.hasSetter("updateTime");
        if(updateTime){
            Object updateTimeValue=metaObject.getValue("updateTime");
            if(Objects.isNull(updateTimeValue)){
                metaObject.setValue("updateTime",DateUtil.dateFmt(new Date()));
            }
        }
        boolean updateBy=metaObject.hasSetter("updateBy");
        if(updateBy){
            Object updateByValue=metaObject.getValue("updateBy");
            if(Objects.isNull(updateByValue)){
                User user=UserManageUtil.get();
                metaObject.setValue("updateBy",user.getUsername());
            }
        }
    }
}
